<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="工作站编码" prop="workstationCode">
        <el-input v-model="queryParams.workstationCode" placeholder="请输入工作站编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="工作站名称" prop="workstationName">
        <el-input v-model="queryParams.workstationName" placeholder="请输入工作站名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="所在车间名称" prop="workshopName">
        <el-select v-model="queryParams.workshopCode" placeholder="请选择车间" clearable style="width: 240px">
          <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
            :value="item.workshopCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属工序" prop="processName">
        <el-select v-model="queryParams.processCode" placeholder="请选择工序" clearable style="width: 240px">
          <el-option v-for="(item, index) in processCodeOptions" :key="item.processId" :label="item.processName"
            :value="item.processCode" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['workstation:workstation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['workstation:workstation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['workstation:workstation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['workstation:workstation:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workstationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工作站ID" align="center" prop="workstationId" />
      <el-table-column label="工作站编码" align="center" prop="workstationCode" />
      <el-table-column label="工作站名称" align="center" prop="workstationName" />
      <el-table-column label="工作站地点" align="center" prop="workstationAddress" />
      <el-table-column label="所在车间名称" align="center" prop="workshopName" />
      <el-table-column label="工序名称" align="center" prop="processName" />
      <el-table-column label="是否启用" align="center" prop="enableFlag">
        <template #default="scope">
          <!-- 三元表达式判断：值为Y显示“是”，值为N显示“否”，其他情况显示原始值（避免异常） -->
          <span :style="getEnableFlagStyle(scope.row.enableFlag)">
            {{ scope.row.enableFlag === 'Y' ? '是' : (scope.row.enableFlag === 'N' ? '否' : scope.row.enableFlag) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['workstation:workstation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['workstation:workstation:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改工作站对话框 -->
    <el-dialog :title="title" v-model="open">
      <el-row :gutter="15">
        <el-form ref="workstationRef" :model="form" :rules="rules" size="default" label-width="150px">
          <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="18">
                <el-form-item label="工作站编号" prop="workstationCode">
                  <el-input v-model="form.workstationCode" type="text" placeholder="请输入工作站编号" clearable
                    :style="{ width: '100%' }"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="自动生成">
                  <el-switch v-model="autoGenerate" @change="handleAutoGenerateChange"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="18">
            <el-form-item label="工作站名称" prop="workstationName">
              <el-input v-model="form.workstationName" type="text" placeholder="请输入工作站名称" clearable
                :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="工作站地点" prop="workstationAddress">
              <el-input v-model="form.workstationAddress" type="text" placeholder="请输入工作站地点" clearable
                :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="所在车间" prop="workshopCode">
              <el-select v-model="form.workshopCode" placeholder="请选择所在车间" clearable :style="{ width: '100%' }"
                @change="handleWorkshopChange">
                <el-option v-for="(item, index) in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                  :value="item.workshopCode" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="所属工序" prop="processCode">
              <el-select v-model="form.processCode" placeholder="请选择所属工序" clearable :style="{ width: '100%' }"
                @change="handleProcessChange">
                <el-option v-for="(item, index) in processCodeOptions" :key="item.processId" :label="item.processName"
                  :value="item.processCode" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag" size="default">
                <el-radio v-for="(item, index) in enableFlagOptions" :key="index" :label="item.value"
                  :disabled="item.disabled">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Workstation">
import { listWorkstation, getWorkstation, delWorkstation, addWorkstation, updateWorkstation, listWorkshop, listProcess } from "@/api/workstation/workstation"
import { get } from "@vueuse/core"

const { proxy } = getCurrentInstance()
function getEnableFlagStyle(enableFlag) {
  if (enableFlag === 'Y') {
    return { color: '#4CAF50' }; // 绿色
  } else if (enableFlag === 'N') {
    return { color: '#F44336' }; // 红色
  }
  return {}; // 其他情况（如null/undefined）用默认样式
}
const workstationList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const workshopOptions = ref([])//车间下拉列表
const processCodeOptions = ref([])//工序下拉列表

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workstationCode: null,
    workstationName: null,
    workshopCode: null,
    workshopName: null,//所属车间
    processCode: null,
    processName: null,//所属工序
  },
  rules: {
    workstationCode: [
      { required: true, message: "工作站编码不能为空", trigger: "blur" }
    ],
    workstationName: [
      { required: true, message: "工作站名称不能为空", trigger: "blur" }
    ],
    workshopName: [
      { required: true, message: "所在车间名称不能为空", trigger: "change" }
    ],
    workshopCode: [
      { required: true, message: "所在车间不能为空", trigger: "change" }
    ],
    processName: [
      { required: true, message: "工序名称不能为空", trigger: "change" }
    ],
    // 修改所属工序的校验规则
    processCode: [
      { required: true, message: "所属工序不能为空", trigger: "change" }
    ],
    warehouseId: [
      { required: true, message: "线边库ID不能为空", trigger: "blur" }
    ],
    locationId: [
      { required: true, message: "库区ID不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "库位ID不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "是否启用不能为空", trigger: "blur" }
    ],
  }
})

// 添加自动生成功能的状态
const autoGenerate = ref(false)
//是否启用状态
const enableFlagOptions = ref([{
  "label": "是",
  "value": "Y"
}, {
  "label": "否",
  "value": "N"
}])


// 自动生成编号的处理函数
function handleAutoGenerateChange(value) {
  if (value) {
    // 自动生成开启时，生成编号并填充
    const generatedCode = generateWorkstationCode()
    form.value.workstationCode = generatedCode
  } else {
    // 自动生成关闭时，清空编号
    form.value.workstationCode = null
  }
}

// 生成工作站编号的函数（示例实现）
function generateWorkstationCode() {
  // 这里可以根据你的业务需求生成编号
  // 示例：使用时间戳生成唯一编号
  const timestamp = new Date().getTime()
  return `WS${timestamp}`
}



const { queryParams, form, rules } = toRefs(data)

/** 查询工作站列表 */
function getList() {
  loading.value = true
  listWorkstation(queryParams.value).then(response => {
    workstationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
//查询车间列表
function getWorkshopList() {
  loading.value = true
  listWorkshop().then(response => {
    workshopOptions.value = response.data
    loading.value = false

  })
}
//查询工序列表
function getProcessList() {
  loading.value = true
  listProcess().then(response => {
    console.log("工序", response);
    processCodeOptions.value = response.data
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    workstationId: null,
    workstationCode: null,
    workstationName: null,
    workstationAddress: null,
    workshopId: null,
    workshopCode: null,
    workshopName: null,
    processId: null,
    processCode: null,
    processName: null,
    warehouseId: null,
    warehouseCode: null,
    warehouseName: null,
    locationId: null,
    locationCode: null,
    locationName: null,
    areaId: null,
    areaCode: null,
    areaName: null,
    enableFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  // 重置自动生成开关
  autoGenerate.value = false
  proxy.resetForm("workstationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.workstationId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工作站"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _workstationId = row.workstationId || ids.value
  getWorkstation(_workstationId).then(response => {
    form.value = response.data

    // 如果返回的数据中没有workshopName和processName，需要根据code查找
    if (form.value.workshopCode && !form.value.workshopName) {
      const selectedWorkshop = workshopOptions.value.find(item => item.workshopCode === form.value.workshopCode)
      if (selectedWorkshop) {
        form.value.workshopName = selectedWorkshop.workshopName
      }
    }

    if (form.value.processCode && !form.value.processName) {
      const selectedProcess = processCodeOptions.value.find(item => item.processCode === form.value.processCode)
      if (selectedProcess) {
        form.value.processName = selectedProcess.processName
      }
    }


    open.value = true
    title.value = "修改工作站"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workstationRef"].validate(valid => {
    if (valid) {
      console.log(form.value);

      if (form.value.workstationId != null) {
        updateWorkstation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWorkstation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}


// 车间选择变化处理函数
function handleWorkshopChange(value) {
  if (value) {
    // 根据选中的车间编码找到对应的车间对象
    const selectedWorkshop = workshopOptions.value.find(item => item.workshopCode === value)
    if (selectedWorkshop) {
      // 保存车间名称到表单中
      form.value.workshopName = selectedWorkshop.workshopName
    }
  } else {
    // 清空选择时，同时清空名称字段
    form.value.workshopName = null
  }
}

// 工序选择变化处理函数
function handleProcessChange(value) {
  if (value) {
    // 根据选中的工序编码找到对应的工序对象
    const selectedProcess = processCodeOptions.value.find(item => item.processCode === value)
    if (selectedProcess) {
      // 保存工序名称到表单中
      form.value.processName = selectedProcess.processName
    }
  } else {
    // 清空选择时，同时清空名称字段
    form.value.processName = null
  }
}




/** 删除按钮操作 */
function handleDelete(row) {
  const _workstationIds = row.workstationId || ids.value
  proxy.$modal.confirm('是否确认删除工作站编号为"' + _workstationIds + '"的数据项？').then(function () {
    return delWorkstation(_workstationIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('workstation/workstation/export', {
    ...queryParams.value
  }, `workstation_${new Date().getTime()}.xlsx`)
}

getList()

getWorkshopList()
getProcessList()
</script>
